/*

Copyright 2009 Nicola Dal Pont

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Version ${MAJOR_VERSION}.${MINOR_VERSION}${BETA_MARK} Build ${BUILD_NUMBER}

*/

package com.astoolkit.xmlmapping
{
   import flash.events.EventDispatcher;
   import flash.events.IEventDispatcher;
   
   import mx.core.IFactory;

   [DefaultProperty("mappings")]
   [Event(name="beforePropertyMap", type="com.astoolkit.xmlmapping.XmlMapPropertyEvent")]
   public class MapPropertyGroup extends EventDispatcher
   {
      public var mappings : Array;
      public var version : String = null;
      public var targetClass : IFactory = null;
      
      public function getProperties( inArray : Array = null ) : Array
      {
         if( inArray == null ) 
         {
            inArray = [];
         }         
         for each( var mapping : IEventDispatcher in mappings )
         {
            if( willTrigger( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP ) &&  
               !mapping.willTrigger( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP ) )
            {
               //group event handling is performed only if 
               //mapping child is not overriding event handling
               mapping.addEventListener( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP, beforePropertyMapHandler );
            }
            if( mapping is MapPropertyGroup )
            {
               MapPropertyGroup( mapping ).getProperties( inArray );
            }
            else
            {
               if( version != null) {
                  MapProperty( mapping ).version = version;
               }
               if( targetClass != null ) {
                  MapProperty( mapping ).targetClass = targetClass;
               }
               inArray.push( mapping ); 
            }
         }
         return inArray;
      }
      
      private function beforePropertyMapHandler( event : XmlMapPropertyEvent ) : void
      {
         if( event.target != this )
         {
            var eventClone : XmlMapPropertyEvent = XmlMapPropertyEvent( event.clone() );
            dispatchEvent( eventClone );
            event.shouldMap = eventClone.shouldMap;
         } 
      }    
   }
}